<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Solve;
use App\Spamrank;
use App\User;
use App\Utils;
use Auth;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use View;

class trainController extends Controller
{
    public function abtest()
    {
        $uuid = "";
        if (!isset($_COOKIE['uuid'])) {
            $uuid = uniqid();
            setcookie("uuid", $uuid);
        } else {
            $uuid = $_COOKIE['uuid'];
        }
        if (strlen($uuid) <= 0) {
            echo "非法的uuid";
            return;
        }
        $ch = $uuid[0];
        $arr = array();
        $arr[] = "霍奇猜想";
        $arr[] = "庞加莱猜想";
        $arr[] = "黎曼假设";
        $arr[] = "BSD猜想";
        $arr[] = "哥德巴赫猜想";
        if ($ch == 'c') {
            echo '字符串"qlcoder"的md5值是多少?';
        } else {
            $a = hexdec($ch) % 5;
            echo "请证明" . $arr[$a] . "并将证明的论文发至oreo@qlcoder.com,等官方审核证明正确后此题设置通过";
        }
        return;
    }

    public function gatools(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }

        $solve = Solve::whereUseridAndTaskid(Auth::user()->id, 95)->get();
        $solve2 = Solve::whereUseridAndTaskid(19, 95)->get();
        $arr = DB::select("select max(score) as score,type from solves where taskid=95 group by type");
        $input = array();
        $max = array();
        foreach ($solve as $s) {
            $input[$s->type] = $s->score;
        }

        foreach ($arr as $s) {
            $max[$s->type] = $s->score;
        }
        return View('train.ga', compact('input'), compact('max'));

        return View::make("train.ga");
    }

    public function heredity(Request $request)
    {
        $input = $request->all();
        if ($input['version'] == "1001") return "1";
        return "您的版本不是最新的,请到qlcoder官网该题目页面下载最新版本的toolbox,新的toolbox可以看到实时的排名";
    }

    public function checkuser(Request $request)
    {
        $input = $request->all();
        Log::info("heredity checkuser:" . var_export($input, true));
        return 1;
    }

    public function checkheredity(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
        $arr = array();
        $arr['699889'] = 1;
        $arr['916829'] = 2;
        $arr['243121'] = 3;
        $arr['1011525'] = 4;
        $arr['116613'] = 5;
        $arr['382260'] = 6;
        $arr['160556'] = 7;
        $arr['164020'] = 8;
        $arr['527724'] = 9;
        $arr['238449'] = 10;
        $input = $request->all();
        Log::info("heredity checkpoint:" . var_export($input, true));
        $md6 = $input['md6'];
        $point = intval(floatval($input['points']) * 100);
        if (!isset($arr[$md6])) return;
        $type = $arr[$md6];
        var_dump(Auth::user()->name);
        $solve = Solve::whereUseridAndTaskidAndType(Auth::user()->id, 95, $type)->get()->first();
        if ($solve == null) {
            $solve = array();
            $solve['userid'] = Auth::user()->id;
            $solve['taskid'] = 95;
            $solve['type'] = $type;
            $solve['answer'] = $input['output'];
            $solve['score'] = $point;
            $data = Solve::create($solve);
        } else if ($solve->score < $point) {
            $solve->score = $point;
            $solve->answer = $input['output'];
            $solve->save();
        }

        return;

    }

	public function qllt()
    {
        return View::make("train.qllt");
    }

    public function qllv1()
    {
        return View::make("train.qllv1");
    }

    public function qllb()
    {
        return View::make("train.qllb");
    }

    public function qlla()
    {
        return View::make("train.qlla");
    }

    public function moducheck(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
        echo '<a href="/train/automodu">点击返回提交页面</a><br>';
        $solve = Solve::whereUseridAndTaskid(Auth::user()->id, 80)->get()->first();
        $content = file_get_contents("/root/work/public/uploads/modu10.data");
        $arr = explode("\n", $content);
        $str = $arr[$solve->score];
        $arr = json_decode($str, true);
        $mp = $arr['map'];
        $map = array();
        for ($i = 0; $i < count($mp); $i++) {
            for ($j = 0; $j < strlen($mp[0]); $j++) {
                $map[$i][$j] = intval($mp[$i][$j]);
            }
        }
        $pieces = $arr['pieces'];
        $modu = intval($arr['modu']);
        $input = $request->all();
        if (!isset($input['solution'])) {
            echo "请带上solution参数";
            die;
        }
        $solu = $input['solution'];
        $ps = count($pieces);
        if (strlen($solu) != $ps * 2) {
            echo "你的答案的长度不对哦,应该是一个长度为" . ($ps * 2) . "的字符串";
            die;
        }
        for ($k = 0; $k < $ps; $k++) {
            $x = hexdec($solu[$k * 2]);
            $y = hexdec($solu[$k * 2 + 1]);
            $piece = $pieces[$k];
            $prr = explode(",", $piece);
            for ($ii = 0; $ii < count($prr); $ii++) {
                for ($jj = 0; $jj < strlen($prr[0]); $jj++) {
                    if ($prr[$ii][$jj] == 'X') {
                        //		var_dump($x." ".$y." ".$ii." ".$jj);
                        if ($x + $ii >= count($mp) || $y + $jj >= strlen($mp[0])) {
                            echo "第" . ($k + 1) . "块piece摆放的位置超出了地图的边界";
                            die;
                        }
                        $map[$x + $ii][$y + $jj]++;
                        if ($map[$x + $ii][$y + $jj] >= $modu) {
                            $map[$x + $ii][$y + $jj] -= $modu;
                        }
                    }
                }

            }
            echo "把第" . ($k + 1) . "块摆在(" . $x . "," . $y . ")位置之后,地图变成了下图所示:<br>";
            for ($i = 0; $i < count($mp); $i++) {
                for ($j = 0; $j < strlen($mp[0]); $j++) {
                    echo $map[$i][$j];
                }
                echo "<br>";
            }
            echo "<br>";

        }
        $cnt = 0;
        for ($i = 0; $i < count($mp); $i++) {
            for ($j = 0; $j < strlen($mp[0]); $j++) {
                $cnt += $map[$i][$j];
            }
        }
        if ($cnt == 0) {
            $solve->score += 1;
            $solve->save();
            Auth::user()->score += $solve->score * 50;
            Auth::user()->save();
            echo "恭喜你,成功通过此关卡";

        } else {
            echo "失败了呢,还是有格子不为0";
        }

    }

    public function mysql(Request $request)
    {
        $input = $request->all();
        $table = intval($input['table']);
        $a = intval($input['a']);
        $b = intval($input['b']);
        if ($b > 100) {
            echo "作为1个运维工程师，你应该知道，mysql返回的数据量太多会给内网流量造成很大的压力！！<br>作为1个业务工程师，你也应该知道不可能有1个页面需要展示超过100个商品的";
            return;
        }
        $str = "select * from items" . $table . " order by favs desc limit " . $a . "," . $b;
        $data = DB::connection('mysql2')->select($str);
        $result = array();
        $result['query'] = $str;
        $result['data'] = $data;
        $t = rand(1, 4);
        sleep($t);
        $result['message'] = "the query cost " . $t . " second";
        return response()->json($result);
    }

    public function crcheck(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
        echo '<a href="/train/autocr">点击返回提交页面</a><br>';
        $solve = Solve::whereUseridAndTaskid(Auth::user()->id, 44)->get()->first();
		$lv=$solve->score;
		if($lv>=300)
		{
			$output=array();
			exec("proxychains4 curl 'http://www.hacker.org/coil/index.php?name=Isun&password=Cw8227%26h%25w&gotolevel=".$lv."&go=Go+To+Level'",$output);
			$str="";
			foreach($output as $o) 
			{
				if(strpos($o,"FlashVars")>0)
				{   
					$str=$o;
					break;
				}   
			}
			$str=substr($str,34);
			$str=substr($str,0,strlen($str)-4);
			$str=str_replace('X','1',$str);
			$str=str_replace('.','0',$str);
			sscanf($str, "x=%d&y=%d&board=%s",$x, $y, $board);
			$str="level=".$lv."&x=".$y."&y=".$x."&map=".$board;
			//$content = file_get_contents("/root/work/public/uploads/automap.txt");
			//$arr = explode("\n", $content);
			if(strlen($str)<1)
			{
				echo "地图错误";die;
			}
		}
		else
		{
			
			$content = file_get_contents("/root/work/public/uploads/automap.txt");
			$arr = explode("\n", $content);
			$str=$arr[$solve->score];
		}
        sscanf($str, "level=%d&x=%d&y=%d&map=%s", $lv, $x, $y, $board);
        $map = array();
        for ($i = 0; $i <= $x + 1; $i++) {
            for ($j = 0; $j <= $y + 1; $j++)
                $map[$i][$j] = 1;
        }
        $need = 0;
        for ($i = 1; $i <= $x; $i++) {
            for ($j = 1; $j <= $y; $j++) {
                $c = $board[($i - 1) * $y + $j - 1];
                $map[$i][$j] = intval($c);
                if ($map[$i][$j] == 0) $need++;
            }
        }
        $input = $request->all();
        $ux = intval($input["x"]);
        $uy = intval($input["y"]);
        if ($ux <= 0 || $ux > $x || $uy <= 0 || $uy > $y) {
            echo "起点超出了地图的边界";
            die;
        }
        if ($map[$ux][$uy] != 0) {
            echo "起点已经有障碍物了";
            die;
        }
        $map[$ux][$uy] = "s";
        $cnt = 1;
        $path = $input["path"];
        $dx = array(-1, 1, 0, 0);//udlr
        $dy = array(0, 0, -1, 1);
        for ($i = 0; $i < strlen($path); $i++) {

            if ($path[$i] == 'u') $dir = 0;
            else if ($path[$i] == 'd') $dir = 1;
            else if ($path[$i] == 'l') $dir = 2;
            else if ($path[$i] == 'r') $dir = 3;
            else {
                echo "错误的方向信息";
                die;
            }
            $tc = 0;
            while ($map[$ux + $dx[$dir]][$uy + $dy[$dir]] === 0) {
                $tc++;
                $ux += $dx[$dir];
                $uy += $dy[$dir];
                $map[$ux][$uy] = 2;
                $cnt++;
            }
            if ($tc == 0) {
                echo "第" . ($i + 1) . "步有问题,已经无法继续向" . $path[$i] . "方向走了<br>";
                die;
            }
        }
        if ($cnt == $need) {

            $path = str_replace('u', "U", $path);
            $path = str_replace('l', "L", $path);
            $path = str_replace('d', "D", $path);
            $path = str_replace('r', "R", $path);

			if($lv>300)
			{
				$str=
            "proxychains4 curl -d 'name=Isun&password=Cw8227%26h%25w&y=" . (intval($input["x"]) - 1) . "&x=" . (intval($input["y"]) - 1) . "&path=" . $path."' 'http://www.hacker.org/coil/index.php'";
            exec($str,$output);
			Log::info("submit level".$lv." ".var_export($output,true));
			Log::info($str);
			}

            $solve->score += 1;
            $solve->save();
            Auth::user()->score += 100;
            Auth::user()->save();
            echo "恭喜你,成功通过此关卡<br>";

        } else {
            echo "还没走完整个地图哦,房间根本没打扫干净<br>";
        }
    }

    public function automodu(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
        $solve = Solve::whereUseridAndTaskid(Auth::user()->id, 80)->get()->first();
        if ($solve == null) {
            $solve = array();
            $solve['userid'] = Auth::user()->id;
            $solve['taskid'] = 80;
            $solve['type'] = 0;
            $solve['answer'] = "";
            $solve['score'] = 0;
            $data = Solve::create($solve);
        }
        $map = file_get_contents("/root/work/public/uploads/modu10.data");
        $arr = explode("\n", $map);
        $input = $request->all();
        if (isset($input['level'])) {
            $solve['level'] = intval($input['level']) - 1;
            if ($solve['level'] > $solve['score']) {
                echo "你还没有权限进入之后的关卡";
                die;
            }
        }

        return View('train.automodu', compact('solve'), compact('arr'));

    }

    public function autocr(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
        $solve = Solve::whereUseridAndTaskid(Auth::user()->id, 44)->get()->first();
        if ($solve == null) {
            $solve = array();
            $solve['userid'] = Auth::user()->id;
            $solve['taskid'] = 44;
            $solve['type'] = 0;
            $solve['answer'] = "";
            $solve['score'] = 0;
            $data = Solve::create($solve);
        }
        $input = $request->all();
		$lv=$solve['score'];
        if (isset($input['level'])) {
            $solve['level'] = intval($input['level']);
			$lv=$solve['level'];
            if ($solve['level'] > $solve['score']) {
                echo "你还没有权限进入之后的关卡";
                die;
            }
        }

		$output=array();
		exec("proxychains4 curl 'http://www.hacker.org/coil/index.php?name=Isun&password=Cw8227%26h%25w&gotolevel=".$lv."&go=Go+To+Level'",$output);
		$str="";
		foreach($output as $o) 
		{
			if(strpos($o,"FlashVars")>0)
			{   
				$str=$o;
				break;
			}   
		}
		$str=substr($str,34);
		$str=substr($str,0,strlen($str)-4);
		$str=str_replace('X','1',$str);
		$str=str_replace('.','0',$str);
		sscanf($str, "x=%d&y=%d&board=%s",$x, $y, $board);
		$ans="level=".$lv."&x=".$y."&y=".$x."&map=".$board;
		//$map = file_get_contents("/root/work/public/uploads/automap.txt");
		//$arr = explode("\n", $map);
		//echo($arr[$solve->score]);
        return View('train.autocr', compact('solve'), compact('ans'));
    }

    public function cr(Request $request)
    {
        if (!Auth::check()) {
            echo '<a href="/auth/login">请先登陆</a>';
            return;
        }
        $solve = Solve::whereUseridAndTaskid(Auth::user()->id, 44)->get()->first();
        if ($solve == null) {
            $solve = array();
            $solve['userid'] = Auth::user()->id;
            $solve['taskid'] = 44;
            $solve['type'] = 0;
            $solve['answer'] = "";
            $solve['score'] = 0;
            $data = Solve::create($solve);
        }
        return View('train.robot', compact('solve'));
    }

	public function modulo(Request $request){
		if (!Auth::check()) {
			return redirect('/home');
		}
		return View('train.modulo');
	}

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function spamrank(Request $request)
    {
//        Log::info(var_export($request->all(), true));
        if ($request->isMethod('post')) {
            $input = $request->all();
            $user = User::whereName($input['user'])->get()->first();
            if ($user == null) {
                echo "该用户还未注册";
                return;
            }
            if ($user->avatar_file_name == null) {
                echo "该用户未上传头像...没有头像怎么评价帅不帅呢！请点击<a href='http://www.qlcoder.com/u/update'>设置</a>上传头像";
                return;
            }
            $user2 = Spamrank::whereUsernameAndDelete($input['user'], 0)->get()->first();
            if ($user2 != null) {
                echo "该用户已经是候选人了";
                return;
            }
            $data = array();
            $data['cnt'] = 1;
            $data['userid'] = $user->id;
            $data['username'] = $user->name;
            Spamrank::create($data);
        } else {
            $input = $request->all();
            if (isset($input['user'])) {
                $user2 = Spamrank::whereUsernameAndDelete($input['user'], 0)->get()->first();
                if ($user2 == null) {
                    echo "该用户还不是候选人";
                    return;
                }
                if ($user2->cnt > 1000) {
                    $answer = md5("ql" . md5($user2->username) . "coder");
                    echo("恭喜你,这题的答案是[" . $answer . "]");
                    return;
                }

                $str = date("Ymd") . $user2->username . $user2->cnt . $input["checkcode"];
                $ans = md5($str);
                if (strpos($ans, "000000") === 0) {
                    $user2->cnt += 1;
                    $user2->save();
                } else {
                    echo "验证码错误<br>";
                    echo '"' . $str . '"的md5值为"' . $ans, '"前6位不都为0哦';
                    return;
                }
            }
        }
        $users = Spamrank::all();
        $userlist = $users->sortbyDesc('cnt');
        return View('train.rank', compact('userlist'));

    }

    public function plus(Request $request)
    {
        $input = $request->all();
        $a = intval($input['a']);
        $b = intval($input['b']);
        return $a + $b;
    }

    public function register(Request $request)
    {
        echo "你已经做到这个系列的第3道了我相信你可以理解的...";
    }

    public function proxy(Request $request)
    {
        $ip = $request->getClientIp();
        if ($ip == '121.201.63.168') {
            echo "恭喜你,本题的答案是 [Squid]";
        } else {
            echo "你现在的ip地址为 :" . $ip . " , 请使用本题给的代理ip进行访问^_^";
        }
    }
	public function sug(Request $request)
	{
		if(!Auth::check())return "please login first";
		$input=$request->all();
		$text=base64_encode(urlencode($input['text']));
		$data=view::make('train.sug',compact('text'));
		$path="/root/test/testfile".Auth::user()->id.".html";
		$myfile = fopen($path, "w");
		fwrite($myfile,$data);
		fclose($myfile);
		$jspath = '/root/work/public/task_135.js';
		$res = exec("/usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs " . $jspath . " " .$path);
	//	var_dump($res);
	//	var_dump(Auth::user()->name);
	//	die;
		if($res==Auth::user()->name)
		{
			return "Congratulations! The answer is cross_site_scripting";
		}
		return $data;

		
	}
	public function callbackkuibu(Request $request)
	{
		if(!Auth::check())
		{
			return "please login first";
		}
		$input=$request->all();
		if(!isset($input['kuibu']))
		{
			return "请输入你要捐赠的跬步的数量";
		}
		$kuibu=$input['kuibu'];//获取用户输入的参数
		$kuibu=trim($kuibu);//去除无用字符
		if(!is_numeric($kuibu))
		{
			return "捐赠的数量是一个数字，请勿填非法字符。";
		}
		if(strpos($kuibu,'X')
			||strpos($kuibu,'x')
			||strpos($kuibu,'e')
			||strpos($kuibu,'E'))
		{
			return "请勿使用16进制或者科学计数法。";
		}
		if($kuibu!=intval($kuibu)||strpos($kuibu,'.'))
		{
			return "捐赠数量必须是整数。";
		}
		if($kuibu<=0)
		{
			return '捐赠数量必须大于0。';
		}
		if($kuibu>Auth::user()->step+Utils::score2step(Auth::user()->score/100))//确认用户必须要拥有足以捐赠的跬步
		{
			return '你不足以捐赠这么多的跬步';
		}
		//去除符号和前导0之后直接算位数
		while($kuibu[0]=='+'||$kuibu[0]=='-'||$kuibu[0]=='0')
		{
			$kuibu=substr($kuibu,1);
		}
		$len=strlen($kuibu);
		$arr=array(
			5=>'你将获得qlcoder的明信片。',
			6=>'你将获得qlcoder的杯子。',
			7=>'你将获得qlcoder的背包。',
			8=>'恭喜你，本题的通关密码为"fuzzphptrim&is_numeric"。',
		);

		for($i=8;$i>4;$i--)
		{
			if($len>=$i)
			{
				return $arr[$i];
				break;
			}
		}
		return "= =!虽然你捐献的跬步不多,仍然感谢你参与。";

	}
	public function sug2(Request $request)
	{
		if(!Auth::check())return "please login first";
		$input=$request->all();
		$text=base64_encode(urlencode($input['text']));
		$data=view::make('train.sug2',compact('text'));
		$path="/root/test/testfile2".Auth::user()->id.".html";
		$myfile = fopen($path, "w");
		fwrite($myfile,$data);
		fclose($myfile);
		$jspath = '/root/work/public/task_135.js';
		$res = exec("/usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs " . $jspath . " " .$path);
		if($res==Auth::user()->name)
		{
			return "Congratulations! The answer is dangerousUPCASE";
		}
		return $data;


	}
	public function ls(Request $request)
	{
		var_dump("1222");
$res = exec("python /usr/local/pypy/pypy/sandbox/task_138_sort_encode/command_check.py /root/test/b61b1bbd5ca489e29d284c66ad1e4eba.py",$output);
var_dump($output);
	}

    public function spider3(Request $request, $id)
    {
        if (intval($id) > 10 || intval($id) < 1) return;
        $speed = array();
        $speed["1"] = 1;
        $speed["2"] = 3;
        $speed["3"] = 3600;
        $speed["4"] = 2400;
        $speed["5"] = 1200;
        $speed["6"] = 300;
        $speed["7"] = 10000;
        $speed["8"] = 86400;
        $speed["9"] = 60;
        $speed["10"] = 10;
        $fh = file_get_contents("/root/work/public/uploads/note.txt");
        $arr = explode("\n", $fh);
        $t = time();
        $tag = intval($t / $speed[$id]) % 1000;
        $tag = ($tag * 9331 * $tag) % 100;
        echo $arr[$tag * 3];
        echo $arr[$tag * 3 + 1];
    }
}
